/*
 * Project: Payment
 * Document: ChainBuilder
 * Date: 2020/9/16 7:41 下午
 * Author: wangbz
 *
 * Copyright © 2020 www.ixiachong.com Inc. All rights reserved.
 * 注意：本内容仅限于深圳瞎充集团有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
package com.chain;

import java.util.Iterator;
import java.util.LinkedList;

public class ChainBuilder<C> {
    private C context;
    private LinkedList<ChainHandler<C>> handlers = new LinkedList<>();

    public ChainBuilder(C context) {
        this.context = context;
    }

    public Chain build() {
        Iterator<ChainHandler<C>> iterator = handlers.iterator();
        return build(iterator);
    }

    private Chain build(Iterator<ChainHandler<C>> iterator) {
        if (iterator.hasNext()) {
            ChainHandler<C> handler = iterator.next();
            return SimpleChain.<C>builder()
                    .context(context)
                    .handler(handler)
                    .next(build(iterator))
                    .build();
        } else {
            return () -> {
            };
        }
    }

    public ChainBuilder<C> next(ChainHandler<C> handler) {
        handlers.add(handler);
        return this;
    }

    public static <C> ChainBuilder<C> context(C context) {
        return new ChainBuilder<>(context);
    }
}
